package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.OrderDto;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;


    @Override
    public void addOrder(Orders orders) {
//        A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findCartByUserId(orders.getUserId());

//        B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(orders.getUserId());

//        C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());

        //定义一个变量保存订单id
        String orderId = UUID.randomUUID().toString();

        //定义一个变量保存总金额
        BigDecimal totalAmount = new BigDecimal("0");

//        D. 遍历所有的购物车的购物项，每一个购物项就对应一个订单详情数据。 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail(); //快速生成setter方法，alt+enter
            orderDetail.setId(UUID.randomUUID().toString());  //订单详情的id ，注意:这里我们使用的uuid.
            orderDetail.setName(shoppingCart.getName()); //菜品名字或者是套餐的名字
            orderDetail.setOrderId(orderId); //订单号
            orderDetail.setDishId(shoppingCart.getDishId());  //菜品的id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());  //套餐的id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor()); //口味
            orderDetail.setNumber(shoppingCart.getNumber());  //数量
            orderDetail.setAmount(shoppingCart.getAmount()); //单价
            orderDetail.setImage(shoppingCart.getImage()); //图片
            //计算每一个购物的总金额
            BigDecimal itemAmount = new BigDecimal(shoppingCart.getNumber() + "").multiply(shoppingCart.getAmount());
            //把每一个购物项的总金额相加
            totalAmount = totalAmount.add(itemAmount);
            orderDetailList.add(orderDetail);
        }

//        E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId); //订单号
        orders.setNumber(orderId); //订单号
        orders.setStatus(1); //状态
        orders.setOrderTime(LocalDateTime.now());  //下单时间
        orders.setCheckoutTime(LocalDateTime.now());  //支付的时间
        orders.setAmount(totalAmount);  //总金额
        orders.setUserName(user.getName()); //订单所属用户的用户名
        orders.setPhone(addressBook.getPhone());  //收货人手机
        orders.setAddress(addressBook.getDetail()); //收货人地址
        orders.setConsignee(addressBook.getConsignee()); //收货人的姓名
        //保存订单
        orderMapper.save(orders);
        //保存订单项
        orderDetailMapper.save(orderDetailList);

//        F. 删除当前用户的购物车列表数据
        shoppingCartMapper.cleanCart(user.getId());

    }


    //后台分页查询订单表
    @Override
    public Page<Orders> findByPage(Integer page, Integer pageSize,String number,String benTime,String endTime) {
        //1.设置当前页和页面大小
        PageHelper.startPage(page,pageSize);

        //2.查询数据
        List<Orders> ordersList = orderMapper.findAll();

        //3.把集合封装到PageInfo对象
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        //4.把PageInfo的数据封装到page对象中
        Page<Orders> ordersPage = new Page<>(pageInfo.getList(),pageInfo.getTotal(),page,pageSize);

        return ordersPage;
    }

    //移动端分页
    @Override
    public Page<OrderDto> findByPageUserid(Integer page, Integer pageSize, Long userId) {
        //1.设置当前页和页面大小
        PageHelper.startPage(page,pageSize);

        //2.查询数据
        List<Orders> ordersList = orderMapper.finduserPage(userId);

        //3.把集合封装到PageInfo对象
        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        List<OrderDto> result = ordersList.stream().map(orders -> {
            String ordersId = orders.getId();//获取订单号
            ArrayList<OrderDetail> orderDetailList = orderDetailMapper.findById(ordersId);
            OrderDto orderDto = new OrderDto();
            orderDto.setOrderDetails(orderDetailList);
            BeanUtils.copyProperties(orders, orderDto);
            return orderDto;
        }).collect(Collectors.toList());

        //4.把PageInfo的数据封装到page对象中
        int pages = pageInfo.getPages();
        Page<OrderDto> ordersPage = new Page<>(result,pageInfo.getTotal(),page,pageSize,pages);

        return ordersPage;
    }
}
